package com.yuzhong.common.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**树的数据结构
 * @author hdy
 * @version 创建时间：2013-3-8 下午1:47:15
 * 树节点
 */
public class TreeNode extends AbstractTree{
	private AbstractTree parent;
	private List<AbstractTree> children =new ArrayList<AbstractTree>();//孩子
	private Object nodeData;//节点内容
	private boolean leaf;//是否是叶子节点
	private int depth;//层
	public TreeNode(){
		
	}
	//把节点dto传进来
	public TreeNode(Object nodeData){
		this.setNodeData(nodeData);
	}
	public int getDepth() {
		return depth;
	}
	public void setDepth(int depth) {
		this.depth = depth;
	}
	public AbstractTree getParent() {
		return parent;
	}
	public List<AbstractTree> getChildren() {
		return children;
	}
 
	public boolean isLeaf() {
		if(children!=null && children.size()>0){
			leaf=false;
		}else{
			leaf=true;
		}
		return leaf;
	}
	public void setParent(AbstractTree parent) {
		this.parent = parent;
		this.setDepth(parent.getDepth()+1);//深度加1
	}
	public void setChildren(List<AbstractTree> children) {
		this.children = children;
	}
 
	public Object getNodeData() {
		return nodeData;
	}
	public void setNodeData(Object nodeData) {
		this.nodeData = nodeData;
	}
	//遍历树
		@Override
		public void iteratorTree(Map<Integer, List<Object>> depthMap) {
			this.dealDepthData(depthMap);
			if(!isLeaf()){
//				System.out.println("深度："+this.getDepth()+"内容："+this.getNodeData());
				for(AbstractTree node:this.getChildren()){
					node.iteratorTree(depthMap);
//					System.out.println("---孩子"+node.getNodeData());
				}
			}else{//遇到叶子打印此节点
//				System.out.println("深度："+this.getDepth()+"内容："+this.getNodeData());
			}
		}
	//遍历树
//	@Override
//	public void iteratorTree(Map<String, List<Dto>> depthMap) {
//		this.dealDepthData(depthMap);
//		if(!isLeaf()){
//			System.out.println("深度："+this.getDepth()+"内容："+this.getNodeData());
//			for(AbstractTree node:this.getChildren()){
//				node.iteratorTree(depthMap);
//			}
//		}else{//遇到叶子打印此节点
//			System.out.println("深度："+this.getDepth()+"内容："+this.getNodeData());
//		}
//	}
	//处理层结构数据：普通树的按层遍历算法
	private void dealDepthData(Map<Integer,List<Object>> depthMap){
		Integer key = this.getDepth();
		if(depthMap.get(key)!=null){
			depthMap.get(key).add(this.getNodeData());
		}else{
			List<Object> ls = new ArrayList<Object>();
			ls.add(this.getNodeData());
			depthMap.put(key, ls);
		}
	}
	@Override
	public TreeNode addChildNode(AbstractTree node) {
		this.getChildren().add(node);
		node.setParent(this);//设置孩子的父节点为自己
		return this;
	}
}
